package com.bskj.kuaifu.MQLister;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.bean.model.PayInfo;
import com.bskj.common.utils.LogUtils;
import com.bskj.common.utils.StringUtils;
import com.bskj.kuaifu.service.IUserInfoService;
import com.github.wxpay.sdk.WXPay;
import com.rabbitmq.client.Channel;

/**
 * 处理余额提现的业务逻辑
 */
public class RefundMessageLister implements ChannelAwareMessageListener {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private WXPay wxPay;

    public void onMessage(Message message, Channel channel) throws Exception {
        String refundStr = new String(message.getBody(), "UTF-8");
        LogUtils.debug(refundStr);
        boolean deleteMessageFlag = true;
        try {
            //List<PayInfo> payInfos = JSONObject.parseArray(refundStr, PayInfo.class);
            PayInfo payInfo = JSONObject.parseObject(refundStr, PayInfo.class);

            Map<String, String> requestData = new HashMap<String, String>();
            String refundNo = StringUtils.getRandomWithTimestamp(32);
            payInfo.setRefundInfoNo(refundNo);
            requestData.put("out_trade_no", payInfo.getOrderNo());
            requestData.put("out_refund_no", payInfo.getRefundInfoNo());
            requestData.put("total_fee", payInfo.getTotalFee() + "");
            requestData.put("refund_fee", payInfo.getRefundFee() + "");
            LogUtils.debug("requestData:" + JSONObject.toJSONString(requestData));

            Map<String, String> resultMap = wxPay.refund(requestData);
            LogUtils.debug("wxPay.refund.resultMap:" + JSONObject.toJSONString(resultMap));
            if (resultMap.get("return_code").equals("SUCCESS") && resultMap.get("result_code").equals("SUCCESS")) {
                userInfoService.setRefundInfoDetail(payInfo);
            } else {
                deleteMessageFlag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            deleteMessageFlag = false;
        }

        if (deleteMessageFlag) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } else {
            //multiple:false:是否批量.true:将一次性拒绝所有小于deliveryTag的消息，requeue：true被拒绝的是否重新入队列，
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
